import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginService } from '../../plugin/service/info';
import { UserInfoEntity } from '../entity/info';
import { UserWxEntity } from '../entity/wx';
import { DictInfoEntity } from '../../dict/entity/info';
import { UserLoginService } from './login';
import axios from 'axios'; // 需要安装 axios

/**
 * 邀请日志信息
 */
@Provide()
export class UserWechatService extends BaseService {
    @Inject()
    pluginService: PluginService;

    @InjectEntityModel(UserInfoEntity)
    userInfoEntity: Repository<UserInfoEntity>;

    @InjectEntityModel(DictInfoEntity)
    dictInfoEntity: Repository<DictInfoEntity>;

    @InjectEntityModel(UserWxEntity)
    userWxEntity: Repository<UserWxEntity>;

    @Inject()
    userLoginService: UserLoginService;

    /**
     * 获取微信小程序用户的openid
     */
    async getOpenid(code) {
        // 获取插件实例
        const instance  = await this.pluginService.getInstance('wx');

        // 获取小程序实例
        const wxApp = await instance.MiniApp();

        const config = wxApp.getConfig();
        const appId = config.items.app_id; // 替换为你的 AppID
        const appSecret = config.items.secret; // 替换为你的 AppSecret
        // 构造请求 URL
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
        try {
            // 发送 GET 请求
            const response = await axios.get(url);
            if (response.data.errcode) {
                console.error('微信接口返回错误:', response.data);
                throw new Error(`微信接口错误: ${response.data.errmsg}`);
            }
            // 如果有openid则查询用户是否存在，并且返回token
            let tokenData = {};
            
            if (response.data.openid) {
                const user = await this.userInfoEntity.findOne({
                    where: {
                        openid: response.data.openid
                    }
                });
                // console.log('user', user)
                if (user) {
                    // 如果用户存在则返回token
                    tokenData = await this.userLoginService.token({id: user.id});
                }
            }
            // console.log('openid', response.data.openid, tokenData);
            // returnData 为 response.data 和 tokenData
            const returnData = {
                ...response.data,
                ...tokenData
            }
            // return response.data;
            return returnData;
        } catch (error) {
            console.error('获取微信小程序用户的openid失败:', error);
            throw error;
        }
    }

    /**
     * 获取微信小程序手机号
     */
    async getPhoneNumber(code, openid, registAdminId = 0, registChannelId = 0, qrcodeId = 0, darenName = '') {
        // 获取插件实例
        const instance  = await this.pluginService.getInstance('wx');

        // 获取小程序实例
        const wxApp = await instance.MiniApp();

        // 获取access_token
        const accessToken = await wxApp.getAccessToken();
        const token = await accessToken.getToken();

        // 构造请求 URL
        const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`;

        try {
            // 发送 POST 请求
            const response = await axios.post(url, {
                code: code
            });

            if (response.data.errcode) {
                throw new Error(`微信接口错误: ${response.data.errmsg}`);
            }
            
            // 根据电话号码更新student的openid
            console.log('手机号获取成功:', response.data.phone_info.phoneNumber);
            if (response.data.phone_info.phoneNumber) {
                const user = await this.userInfoEntity.find({ where: { phone: response.data.phone_info.phoneNumber } });
                let userid = 0;
                if (user.length <= 0) {
                    console.log('手机号不存在', registAdminId, registChannelId, qrcodeId, darenName)
                    // 如果没有学员则新建一个学员
                    const newUser = new UserInfoEntity();
                    newUser.phone = response.data.phone_info.phoneNumber;
                    newUser.nickName = '新用户'; // 替换为实际的姓名
                    newUser.openid = openid;
                    newUser.qrcodeId = qrcodeId;
                    newUser.darenName = darenName;
                    newUser.registAdminId = registAdminId;
                    newUser.registChannelId = registChannelId;
                    const result = await this.userInfoEntity.save(newUser); // 保存新的实体
                    userid = result.id;
                    console.log('微信小程序手机号更新成功:', openid, result);
                } else {
                    // 更新所有学员的openid
                    for (const u of user) {
                        u.openid = openid;
                        await this.userInfoEntity.save(u);
                        userid = u.id;
                    }
                    console.log('微信小程序手机号更新成功:', openid, user);
                }
                return this.userLoginService.token({id: userid})
            }
            throw new Error('获取手机号失败，请稍后再试');
        } catch (error) {
            console.error('获取微信小程序手机号失败:', error);
            throw error;
        }
    }

    // 注册
    async registerByPhone(code, openid, registAdminId = 0, registChannelId = 0, qrcodeId = 0, darenName = '', nickName = '新用户', birthday = null, phone = null) {

        // 获取插件实例
        const instance  = await this.pluginService.getInstance('wx');

        // 获取小程序实例
        const wxApp = await instance.MiniApp();

        // 获取access_token
        const accessToken = await wxApp.getAccessToken();
        const token = await accessToken.getToken();

        // 构造请求 URL
        const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`;

        try {
            // 发送 POST 请求
            // const response = await axios.post(url, {
            //     code: code
            // });

            // if (response.data.errcode) {
            //     throw new Error(`微信接口错误: ${response.data.errmsg}`);
            // }
            
            // 根据电话号码更新student的openid
            // console.log('手机号获取成功:', response.data.phone_info.phoneNumber);
            if (phone) {
                const user = await this.userInfoEntity.find({ where: { phone: phone } });
                let userid = 0;
                if (user.length <= 0) {
                    console.log('手机号不存在', registAdminId, registChannelId, qrcodeId, darenName)
                    // 如果没有学员则新建一个学员
                    const newUser = new UserInfoEntity();
                    newUser.phone = phone;
                    newUser.nickName = nickName; // 替换为实际的姓名
                    newUser.openid = openid;
                    newUser.qrcodeId = qrcodeId;
                    newUser.darenName = darenName;
                    newUser.registAdminId = registAdminId;
                    newUser.registChannelId = registChannelId;
                    newUser.birthday = birthday;
                    const result = await this.userInfoEntity.save(newUser); // 保存新的实体
                    userid = result.id;
                    console.log('微信小程序手机号更新成功:', openid, result);
                } else {
                    // 更新所有学员的openid
                    for (const u of user) {
                        u.openid = openid;
                        await this.userInfoEntity.save(u);
                        userid = u.id;
                    }
                    console.log('微信小程序手机号更新成功:', openid, user);
                }
                return this.userLoginService.token({id: userid})
            }
            throw new Error('获取手机号失败，请稍后再试');
        } catch (error) {
            console.error('获取微信小程序手机号失败:', error);
            throw error;
        }
    }

    async loginByOpenidGetStudentList(openid: string) {
        // try {
        //     // 根据 openid 查询学员列表
        //     const studentList = await this.studentStudentEntity.find({
        //         where: { openid: openid },
        //         select: ['id', 'name', 'shop'] // 请根据实际字段名修改
        //     });
        //     // 获取所有门店
        //     const shops = await this.dictInfoEntity.find({
        //         where: {
        //         typeId: 27
        //         },
        //     });

        //     let result = [];
        //     // 遍历学员列表，为每个学员添加门店名称
        //     for (const student of studentList) {
        //         const shop = shops.find(s => s.id === student.shop); // 查找门店名称
        //         result.push({
        //             id: student.id,
        //             name: student.name,
        //             gender: student.gender,
        //             avatar: student.gender === 1 ? 'https://alicdn.joyballet.cn/eyemanager/wechat/avatar/girl_avatar.jpg' : 'https://alicdn.joyballet.cn/eyemanager/wechat/avatar/boy_avatar.jpg',
        //             shop: shop ? shop.name : '未知门店' // 如果找不到门店名称，则显示'未知门店'
        //         })
        //     }
    
        //     // if (result.length === 0) {
        //     //     console.warn('未找到该 openid 对应的学员信息');
        //     // }
    
        //     return result;
        // } catch (error) {
        //     // console.error('使用 openid 登录获取学员列表失败:', error);
        //     throw error;
        // }
    }

    async getWechatConfig() {
        return {
            // chatOpen: '我是特别牛逼的蒋先生，你要是认识我，那真是三生有幸啊。来来来，萍水相逢何必曾相识，有啥问题我来给你解答一下。',
            // chatTitle: '蒋先生-双博视专家',
            // chatSubTitle: 'AI数字分身验证'
            chatOpen: '你好，我是双博视眼科专家数字人，我都将凭借专业的知识，为你提供全面、精准且个性化的儿童眼部健康服务，有任何疑问可以随时沟通。',
            chatTitle: '蒋医生-双博视专家',
            chatSubTitle: 'Jiang Doctor - Digital Avatar'
        }
    }

}
